package com.yy.tech.data.logger.context;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class SpringContextEnvironmentApplicationListener implements EnvironmentPostProcessor , SmartApplicationListener {

    private List<Class> sourceTypes= Stream.of(ApplicationContext.class,SpringApplication.class).collect(Collectors.toList());
    private List<Class> eventTypes = Stream.of(ApplicationEnvironmentPreparedEvent.class).collect(Collectors.toList());
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        SpringContext.setEnvironment(environment);
    }

    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return eventTypes.stream().anyMatch(t->t.isAssignableFrom(eventType));
    }

    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        return sourceTypes.stream().anyMatch(t-> t.isAssignableFrom(sourceType));
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE+5;
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationEnvironmentPreparedEvent){
            SpringContext.setEnvironment(((ApplicationEnvironmentPreparedEvent) event).getEnvironment());
        }
    }
}
